<template>
  <div class="table-warp">
    <div class="table-head">
      <span style="margin-left: 10px">{{$t('webchat.lastTimeRefreshTime')}} {{refreshDate}}</span>
      <a href="javascript:;" class="refresh fl" @click.stop="refreshData"><i class="iconfont icon-shuaxin"></i> {{$t('public.refresh')}}</a>
      <a href="javascript:;" class="refresh fr" @click.stop="showCheckList">{{$t('webchat.showRow')}} <i class="iconfont" :class="showCheckFlag ? 'icon-zhankai1' : 'icon-shouqi'"></i></a>
      <div v-show="showCheckFlag" class="chooseTableHead">
        <el-checkbox-group v-model="dataTableList">
          <el-col :span="8"><el-checkbox label="number">{{$t('webchat.webchatTableNumber')}}</el-checkbox></el-col>
          <!--<el-col :span="8"><el-checkbox label="customerIntention">{{$t('webchat.customerIntention')}}</el-checkbox></el-col>-->
          <el-col :span="8"><el-checkbox label="area">{{$t('webchat.visitorArea')}}</el-checkbox></el-col>
          <el-col :span="8"><el-checkbox label="pages">{{$t('webchat.customerTrackBrowseRemark')}}</el-checkbox></el-col>
          <el-col :span="8"><el-checkbox label="seokeywords">{{$t('webchat.inviteKeywords')}}</el-checkbox></el-col>
          <el-col :span="8"><el-checkbox label="pageSource">{{$t('report.imSourceType')}}</el-checkbox></el-col>
          <el-col :span="8"><el-checkbox label="converNum">{{$t('webchat.converNum')}}</el-checkbox></el-col>
          <el-col :span="8"><el-checkbox label="invitationNum">{{$t('webchat.invitationNum')}}</el-checkbox></el-col>
          <!--<el-col :span="8"><el-checkbox label="visiteNum">{{$t('webchat.visiteNum')}}</el-checkbox></el-col>-->
          <!--<el-col :span="8"><el-checkbox label="visitePageCount">{{$t('webchat.visitePageCount')}}</el-checkbox></el-col>-->
          <el-col :span="8"><el-checkbox label="browser">{{$t('webchat.browser')}}</el-checkbox></el-col>
          <el-col :span="8"><el-checkbox label="os">{{$t('webchat.osInfo')}}</el-checkbox></el-col>
          <div style="text-align: center;">
            <el-button class="primary_btn" @click="cancelChoose">{{$t('public.cancel')}}</el-button>
            <el-button class="primary_btn" type="primary" @click="saveChoose">{{$t('public.save')}}</el-button>
          </div>
        </el-checkbox-group>
      </div>
    </div>
    <el-table
      :data="tableData"
      size="mini"
      style="width: 100%"
      v-loading="loading || conversationData.loading"
      ref="table"
      :row-key="rowKey"
      @selection-change="handleSelectionChange">
      <el-table-column v-if="tableList.length" :selectable="selectableHandel" :reserve-selection="reserveSelection" type="selection" min-width="50"></el-table-column>
      <el-table-column v-if="tableList.indexOf(item.status) !== -1" v-for="item in tableHeadConfig" :key="item._id" :prop="item.status" :label="item.label" :min-width="item.width">
        <template scope="scope">
          <el-popover v-if="item.status === 'pages'" popper-class="browse_track_popover_zindex" trigger="hover" placement="left">
            <div class="popper_box" v-on:scroll="timeScroll($event, scope.row)">
              <webchat-time-line :ubaInfoListPages="scope.row.allTrack" :isInvite="isInvite"></webchat-time-line>
            </div>
            <div slot="reference" class="name-wrapper">
              <p v-for="item in scope.row.track" :key="item._id">
                <a href="javascript:;" style="margin-right: 5px"><i class="iconfont icon-liulanguiji1"></i> 轨迹</a>
                <span>{{item.title}}</span>
              </p>
            </div>
          </el-popover>
          <a v-else-if="item.status === 'pageSource'" :href="scope.row.pageSource" target="_blank">{{scope.row.pageSourceTitle}}</a>
          <div v-else>{{scope.row[item.status]}}</div>
        </template>
      </el-table-column>
    </el-table>
    <!--<el-table
      v-if="false"
      :data="tableData"
      style="width: 100%"
      v-loading="loading || conversationData.loading"
      ref="table"
      :row-key="rowKey"
      @selection-change="handleSelectionChange">
      <el-table-column :selectable="selectableHandel" :reserve-selection="reserveSelection" type="selection" min-width="50"></el-table-column>
      <el-table-column v-if="tableList.indexOf('number') !== -1" prop="number" :label="$t('webchat.webchatTableNumber')" width="70"></el-table-column>
      &lt;!&ndash;<el-table-column v-if="tableList.indexOf('customerIntention') !== -1" prop="number" :label="$t('webchat.customerIntention')" width="100"></el-table-column>&ndash;&gt;
      <el-table-column v-if="tableList.indexOf('area') !== -1" prop="address" :label="$t('webchat.visitorArea')" width="120"></el-table-column>
      <el-table-column v-if="tableList.indexOf('pages') !== -1" :label="$t('webchat.customerTrackBrowseRemark')" min-width="100">
        <template scope="scope">
          <el-popover popper-class="time_start_popper" trigger="hover" placement="left">
            <div class="popper_box" v-on:scroll="timeScroll($event, scope.row)">
              &lt;!&ndash;<ul>
                <li v-for="item in scope.row.allTrack">
                  <span>{{item.timeStart}}</span>
                  <span class="stayTime" v-if="item.stayTime">{{$t('webchat.stay')}}  {{item.stayTime}}</span>
                  <span>{{item.title}}</span>
                </li>
              </ul>&ndash;&gt;
              <webchat-time-line :ubaInfoListPages="scope.row.allTrack" :isInvite="isInvite"></webchat-time-line>
            </div>
            <div slot="reference" class="name-wrapper">
              <p v-for="item in scope.row.track">
                &lt;!&ndash;<span>{{item.timeStart}}</span>&ndash;&gt;
                &lt;!&ndash;<span class="stayTime" v-if="item.stayTime">{{$t('webchat.stay')}} {{item.stayTime}}</span>&ndash;&gt;
                <a href="javascript:;" style="margin-right: 5px"><i class="iconfont icon-liulanguiji1"></i> 轨迹</a>
                <span>{{item.title}}</span>
              </p>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column v-if="tableList.indexOf('seokeywords') !== -1" prop="keywords" :label="$t('webchat.inviteKeywords')" min-width="120"></el-table-column>
      <el-table-column v-if="tableList.indexOf('pageSource') !== -1" prop="pageSource" :label="$t('report.imSourceType')" min-width="100">
        <template scope="scope">
          <a :href="scope.row.pageSource" target="_blank">{{scope.row.pageSourceTitle}}</a>
        </template>
      </el-table-column>
      <el-table-column v-if="tableList.indexOf('converNum') !== -1" prop="converNum" :label="$t('webchat.converNum')" min-width="90"></el-table-column>
      <el-table-column v-if="tableList.indexOf('invitationNum') !== -1" prop="invitationNum" :label="$t('webchat.invitationNum')" min-width="90"></el-table-column>
      &lt;!&ndash;<el-table-column v-if="tableList.indexOf('visiteNum') !== -1" prop="visiteNum" :label="$t('webchat.visiteNum')" min-width="90"></el-table-column>&ndash;&gt;
      &lt;!&ndash;<el-table-column v-if="tableList.indexOf('visitePageCount') !== -1" prop="keywords" :label="$t('webchat.visitePageCount')" min-width="90"></el-table-column>&ndash;&gt;
      <el-table-column v-if="tableList.indexOf('browser') !== -1" prop="browserName" :label="$t('webchat.browser')" min-width="100"></el-table-column>
      <el-table-column v-if="tableList.indexOf('os') !== -1" prop="osInfo" :label="$t('webchat.osInfo')" min-width="100"></el-table-column>
      &lt;!&ndash;<el-table-column
        :label="$t('webchat.inviteStatus')"
        width="120">
        <template scope="scope">
          <span :class="{'success': scope.row.status === 'webchat.inviteStatusSuccess', 'typing': scope.row.status === 'webchat.inviteStatusTypingTable'}">
            {{ $t(scope.row.status) }}
          </span>
        </template>
      </el-table-column>&ndash;&gt;
    </el-table>-->
    <div class="table-invite">
      <p>
        <span>{{$t('webchat.inviteLanguage')}}</span>
        <span class="invited" v-if="!multipleSelection.length">{{$t('webchat.inviteSelectedCustomerIsNull')}}</span>
      </p>
      <el-input class="input-box" :placeholder="$t('public.pleaseEnter')" v-model.trim="invitedInfo">
        <el-button class="input-btn"
                   :disabled="!btnActive"
                   :class="{'input-btn-active': btnActive}"
                   slot="append" @click="sendInvited">{{$t('webchat.sendInvited')}}</el-button>
      </el-input>
    </div>
  </div>
</template>
<script>
  /**
   * 会话邀请弹窗table组件
   */
  import {getFormatDateTime, deepClone} from '@/utils/m7Utils'
  import WebchatTimeLine from '../../ui-modules/timeLine/webChatTimeLine.vue'
  export default {
    name: 'WebchatTable',
    props: {
      conversationData: Object
    },
    components: {
      WebchatTimeLine
    },
    computed: {
      btnActive () {
        return this.invitedInfo && this.multipleSelection.length
      },
      tableData () { // 处理table内的数据
        let list = []
        let sessionList = this.$store.state.webchat.inviteUbaSessionList.list
        if (this.$store.state.webchat.inviteUbaSessionList.tableList) {
          this.tableList = this.$store.state.webchat.inviteUbaSessionList.tableList
        }
        this.dataTableList = deepClone(this.tableList)
        for (let i = 0; i < sessionList.length; i++) {
          let obj = {}
          let item = sessionList[i]
          obj.number = i + 1
          obj._id = item._id
          obj.ubaSessionId = item.pages[0] ? item.pages[0].sessionId : ''
          obj.area = item.platform.area
          obj.browser = item.platform.browserName
          obj.os = item.platform.osInfo
          obj.pageSource = item.pages[0] ? item.pages[0].currentUrl : ''
          obj.pageSourceTitle = item.pages[0] ? item.pages[0].title : ''
          obj.invitationNum = item.invitationNum
          obj.converNum = item.converNum
          let seosource = item.platform.seosource ? item.platform.seosource : ''
          let seokeywords = item.platform.seokeywords ? item.platform.seokeywords : ''
          obj.seokeywords = seosource + ' ' + seokeywords
          obj.status = item.status
          obj.track = []
          obj.allTrack = []
          for (let j = 0; j < item.pages.length; j++) {
            let pagesObj = {}
            let data = item.pages[j]
            pagesObj.title = data.title
            pagesObj.timeStart = data.timeStart
            pagesObj._id = data._id
            if (data.stayTime) {
              pagesObj.stayTimeDesc = data.stayTime
            }
            obj.track.push(pagesObj)
            obj.allTrack.push(pagesObj)
          }
          obj.track = obj.track.splice(0, 1)
          list.push(obj)
        }
        return list
      }
    },
    data () {
      return {
        multipleSelection: [],
        userSessionIds: [],
        invitedInfo: '',
        loading: false,
        refreshDate: '',
        reserveSelection: true,
        dataTableList: ['number', 'area', 'pages', 'seokeywords', 'pageSource', 'converNum'],
        tableList: [],
        showCheckFlag: false,
        isInvite: true,
        tableHeadConfig: [
          {
            status: 'number',
            label: this.$t('webchat.webchatTableNumber'),
            width: 70
          },
          {
            status: 'area',
            label: this.$t('webchat.visitorArea'),
            width: 120
          },
          {
            status: 'pages',
            label: this.$t('webchat.customerTrackBrowseRemark'),
            width: 110
          },
          {
            status: 'seokeywords',
            label: this.$t('webchat.inviteKeywords'),
            width: 130
          },
          {
            status: 'pageSource',
            label: this.$t('report.imSourceType'),
            width: 100
          },
          {
            status: 'converNum',
            label: this.$t('webchat.converNum'),
            width: 90
          },
          {
            status: 'invitationNum',
            label: this.$t('webchat.invitationNum'),
            width: 90
          },
          {
            status: 'browser',
            label: this.$t('webchat.browser'),
            width: 100
          },
          {
            status: 'os',
            label: this.$t('webchat.osInfo'),
            width: 100
          }
        ]
      }
    },
    methods: {
      handleSelectionChange (val) {
        this.multipleSelection = val
      },
      sendInvited () { // 发送会话邀请
        // v22.1 增加发送会话邀请埋点
        const account = this.$store.state.session.account.account
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PE-发送会话邀请', account])
        let sessionIds = []
        if (this.multipleSelection.length) {
          this.multipleSelection.forEach((item, index) => {
            sessionIds.push(item._id)
          })
          let inviteMessage = this.invitedInfo
          let sessionIdArr = []
          let content = this.invitedInfo
          this.userSessionIds = sessionIdArr.concat(sessionIds)
          this.$store.dispatch('inviteCustomersSensitiveWords', {content}).then(res => {
            if (res && res.success) {
              this.$store.dispatch('inviteCustomers', {sessionIds, inviteMessage}).then((res) => {
                if (res.success) {
                  this.$refs.table.clearSelection(this.multipleSelection)
                  this.invitedInfo = ''
                }
              })
            }
          })
        }
      },
      refreshData () { // 刷新访客信息
        this.showCheckFlag = false
        let nowdate = new Date()
        this.loading = true
        this.refreshDate = getFormatDateTime(nowdate).split(' ')[1]
        this.$store.dispatch('getSessionsByAccount', {pageSize: 10, page: 1, tableList: this.dataTableList}).then((res) => {
          if (res && res.success) {
            this.tableList = this.dataTableList
            this.loading = false
          }
        })
      },
      showCheckList () { //
        this.showCheckFlag = !this.showCheckFlag
      },
      cancelChoose () {
        this.dataTableList = deepClone(this.tableList)
        this.showCheckFlag = false
      },
      saveChoose () {
        this.refreshData()
      },
      selectableHandel (row, index) { // 禁用已经邀请过的访客
        let flag = true
        this.userSessionIds.forEach((item, index) => {
          if (item === row._id) {
            flag = false
            return false
          }
        })
        return flag
      },
      rowKey (row) {
        return row._id
      },
      timeScroll (event, row) { // 滚动加载更多浏览轨迹
        let nScrollHight = 0
        let nScrollTop = 0
        let nDivHight = event.target.offsetHeight
        nScrollHight = event.target.scrollHeight
        nScrollTop = event.target.scrollTop
        if (nScrollTop + nDivHight + 2 >= nScrollHight) { // 解决不同分辨率下scrollTop的差异
//          this.$store.dispatch('getMoreTrack', {sid: row.ubaSessionId})
        }
      }
    },
    mounted () {
      let nowdate = new Date()
      this.refreshDate = getFormatDateTime(nowdate).split(' ')[1]
    }
  }
</script>

<style lang="stylus" scope>
  @import "../../../assets/common.styl"
  .table-warp
    padding 20px
    .table-head
      border 1px solid rgb(223, 236, 235)
      border-bottom none
      height 50px
      line-height 50px
      padding 0 15px
      color $cf-level2
    .refresh
      display inline-block
      cursor pointer
      color $c-main
      .iconfont
        font-size 12px
    .success
      color #95d893
    .typing
      color #f8c991
    .table-invite
      p
        line-height 30px
        margin-top 10px
        span
          color $cf-gray4
        .invited
          color #9fd6eb
      .input-btn
        background $c-border1
        color $cf-white
      .input-btn-active
        background $c-main
    .chooseTableHead
      width 390px
      background #fff
      z-index 100
      position absolute
      right 20px
      padding: 20px 10px
      box-sizing: border-box
      box-shadow 0 0 14px 1px rgba(0,0,0,.25)
      .el-col-8
        padding-left 20px
  .stayTime
    color #f6c277
  .popper_box
    max-height 200px
    overflow-y scroll
    overflow-x hidden
</style>
